var locPicker;
(function($, doc) {
	
	$.init({
		// statusBarBackground: '#067FFA'
	});
	$.plusReady(function() {
		var accountBox = doc.getElementById('account');
		var passwordBox = doc.getElementById('password');
		// 开始读取用户 判断是否有有效登录
		var authedUser = JSON.parse(localStorage.getItem('$user') || '{}');
		var authed = authedUser.usercode && authedUser.password;
		var settings = app.getSettings();
		if (authed) {
			// console.log('已登录:',JSON.stringify(authedUser))
			accountBox.value = authedUser.usercode;
			if (settings.autoLogin == true) {
				passwordBox.value = authedUser.password;
				setTimeout(function() {
					$.trigger(loginButton, 'tap');
				}, 500);
			}
		} else {
			console.log('未登录')
			accountBox.value = '';
			passwordBox.value = '';
		}

		// users = [];
		// users.push(loginInfo);

		// close splash
		setTimeout(function() {
			//关闭 splash
			plus.navigator.closeSplashscreen();
		}, 600);
		//检查 "登录状态" 结束

		var loginButton = doc.getElementById('login');
		var autoLoginButton = doc.getElementById("autoLogin");
		// 登录
		loginButton.addEventListener('tap', function(event) {
			loginBtnTapped()
		});
		$.enterfocus('#login-form input', function() {
			$.trigger(loginButton, 'tap');
		});
		var autoLoginButton = doc.getElementById('autoLogin');
		var rememberMe = doc.getElementById('rememberMe');
		// autoLoginButton.classList[settings.autoLogin ? 'add' : 'remove']('mui-active')
		autoLoginButton.classList.add(settings.autoLogin ? 'nur-check-all' : 'nur-check-none')
		rememberMe.addEventListener('tap', function(event) {
			setTimeout(function() {
				if (autoLoginButton.classList.contains('nur-check-all')) {
					autoLoginButton.classList.remove('nur-check-all');
					autoLoginButton.classList.add('nur-check-none');
					settings.autoLogin = false;
				} else {
					autoLoginButton.classList.add('nur-check-all');
					autoLoginButton.classList.remove('nur-check-none');
					settings.autoLogin = true;
				}
				app.setSettings(settings);
			}, 50);
		}, false);

		//
		var backButtonPress = 0;
		// $.back = function(event) {
		// 	backButtonPress++;
		// 	if (backButtonPress == 1) {
		// 		plus.runtime.quit();
		// 	}
		// 	setTimeout(function() {
		// 		backButtonPress = 0;
		// 	}, 1000);
		// 	return false;
		// };
	});

	function loginBtnTapped() {
		var accountBox = doc.getElementById('account');
		var passwordBox = doc.getElementById('password');
		var loginInfo = {
			usercode: accountBox.value,
			password: passwordBox.value
		};
		
		var locBtn = document.getElementById("selectLocBtn");
		var userInfo = app.getState();
		if(userInfo){
			var choseWardId = userInfo.loginWardId;
			var choseWardDesc = userInfo.loginWardDesc;
			if(choseWardId && choseWardDesc){
				locBtn.innerHTML = choseWardDesc
				toMain()
				return
			}
		}
		
		app.login(loginInfo, function(err) {
			if (err) {
				var id = parseInt(err);
				if (isNaN(id)) {
					mui.toast(err);
					return;
				}
			}
			var wardList = app.getState()['WardList']
			if(typeof(wardList) == 'string'){  // 后端应该输出对象，不应该是现在的字符串
				wardList = wardList.replace(/'/g,'"');
				try{
					const wards = JSON.parse(wardList);
					updateLoginUIs(wards)
				}catch(e){
					console.log("JSON解析错误！",e)
				}
			}
		});
	}

	function updateLoginUIs(wardList) {
		var user = app.getState();
		var locBtn = document.getElementById("selectLocBtn");
		locBtn.innerHTML = user.loginWardDesc
		var defalutWardID = user.loginWardId;
		
		if(wardList.length > 0){
			locBtn.removeAttribute("disabled");
			const pickerJson = wardList.map(ward => ({
				value: ward.WardId,
				text: ward.WardDesc
			}))
			// 给picker一个默认的选中
			var index = pickerJson.findIndex(ward => ward.value === defalutWardID)
			locPicker = new $.PopPicker();
			locPicker.setData(pickerJson);
			locPicker.pickers[0].setSelectedIndex(index, 500);
			
			locBtn.addEventListener('tap',function(){
				locPicker.show(function(selectedItem) {
					locBtn.innerHTML = selectedItem[0].text;
					user.loginWardDesc = selectedItem[0].text;
					user.loginWardId = selectedItem[0].value;
					app.setState(user)
				});
			})
		}
	}

	function toMain() {
		plus.nativeUI.showWaiting('正在进入')
		setTimeout(function() {
			plus.webview.currentWebview().close()
			plus.nativeUI.closeWaiting()
			$.openWindow({
				url: 'index.html',
				id: 'index',
				preload: true,
				show: {
					aniShow: 'pop-in'
				},
				styles: {
					popGesture: 'none' //禁用手势返回
				},
				waiting: {
					autoShow: false
				}
			});
		},200);
	};
}(mui, document));